package com.samebuilding.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.samebuilding.dao.PublicMesDAO;
import com.samebuilding.domain.PublicMessage;

public class PublicMesDAOImpl extends HibernateDaoSupport implements PublicMesDAO {

	public void save(PublicMessage pm) {
		this.getHibernateTemplate().save(pm);
	}

	public List getMessage() {
		List message = null;
		message = this.getHibernateTemplate().find("from PublicMessage");
		return message;
	}

	public void removeMessage(PublicMessage pm) {
		this.getHibernateTemplate().delete(pm);
	}
	public PublicMessage getLastessage(final int type){
		List message=this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
			throws HibernateException, SQLException {
				Query q=session.createQuery("from PublicMessage as p where p.type=? order by p.date desc");
				q.setParameter(0, type);
				q.setMaxResults(1);
				return q.list();
			}

		});
		System.out.println(message.size());
		if(message!=null&&message.size()>0)
			return (PublicMessage)message.get(0);
		return null;

	}

}
